package outoforder.leetcode01;

import org.junit.Test;

import java.util.HashMap;

/**
 * @author shhjiang_001
 * @create 2020-07-12 20:32
 */
// 前缀合
public class Solution560 {
    public int subarraySum1(int[] nums, int k) {
        int n = nums.length;
        int[] sum = new int[n + 1];
        int res = 0;
        sum[0] = 0;
        for (int i = 0; i < n; i++) {
            sum[i+1] = sum[i]+nums[i];
        }
        for (int i = 0; i < n + 1; i++) {
            for (int j = 0; j < i ; j++) {
                if (sum[i] - sum[j] == k) res++;
            }
        }
        return res;
    }
    public int subarraySum(int[] nums, int k) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0,1);
        int ans = 0;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum+nums[i];
            // 比sum恰好小K的前缀合数量，正是符合要求的数量。
            if (map.containsKey(sum-k)){
                ans = ans + map.get(sum-k);
            }
            // 把所有的前缀和都记在hashmap中
            map.put(sum,map.getOrDefault(sum,0)+1);
        }
        return ans;
    }
    @Test
    public void test(){
        System.out.println(subarraySum(new int[]{3, 5, 2, -2, 4, 1}, 5));
    }
}
